import 'package:dio/dio.dart';
import 'package:mall/core/models/me.dart';
import 'package:mall/core/models/user_total.dart';
import 'package:mall/core/services/api.dart';
import 'package:mall/core/services/auth.dart';
import 'package:mall/core/providers/view_model.dart';

/// 我的 个人信息、统计信息
class MineModel extends ViewModel {
  final Auth auth;
  final Api api;
  String _errorMessage;
  Me _me;
  UserTotal _userTotal;

  MineModel(this.auth, this.api) : super() {
    _initData();
  }

  String get errorMessage => _errorMessage;

  Me get me => _me;

  UserTotal get userTotal => _userTotal;

  Future<ViewState> _initData() async {
    viewState = ViewState.busy;
    try {
      _me = await auth.me(cancelToken);
      _userTotal = await api.userTotal(cancelToken);
      viewState = ViewState.success;
    } catch (e) {
      _errorMessage = e is DioError ? e.message : e.toString();
      viewState = ViewState.error;
    }
    return viewState;
  }

  Future<ViewState> refreshData() async {
    try {
      _me = await auth.me(cancelToken);
      _userTotal = await api.userTotal(cancelToken);
      viewState = ViewState.success;
    } catch (e) {
      _errorMessage = e is DioError ? e.message : e.toString();
    }
    return viewState;
  }
}
